package com.jason.kotlin.meta.architecture2.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.jason.kotlin.meta.architecture2.api.ApiSource
import com.jason.kotlin.meta.architecture2.api.HomeService
import com.jason.kotlin.meta.architecture2.model.ArticleBean
import com.jason.kotlin.meta.architecture2.model.BannerBean
import com.jason.kotlin.meta.architecture2.model.WanDataWrapper
import com.jason.kotlin.meta.architecture2.repository.HomeApi
import com.jason.kotlin.meta.architecture2.repository.HomeApiImpl
import com.jason.library.common.base.PageStatus
import kotlinx.coroutines.launch
import java.lang.Exception

class HomeViewModel(application: Application) : AndroidViewModel(application) {

    //页面状态变化
    val pageStatusData = MutableLiveData<PageStatus>()

    val bannerData = MutableLiveData<WanDataWrapper<List<BannerBean>>>()


    val articleData = MutableLiveData<WanDataWrapper<List<ArticleBean>>>()

    private var homeApi : HomeApi

    private var curPage: Int = 0

    init {
        val homeService = ApiSource.getWanAndroidService(HomeService::class.java)
        homeApi = HomeApiImpl(homeService)
    }

    fun loadData() {
        curPage = 0
        viewModelScope.launch {
            pageStatusData.postValue(PageStatus.loading())
            try {
                val bannerResponse = homeApi.getBanners()
                val articleResponse = homeApi.getArticles(curPage)

                bannerData.postValue(WanDataWrapper.success(bannerResponse.data))
                articleData.postValue(WanDataWrapper.success(articleResponse.data.datas))

                pageStatusData.postValue(PageStatus.success())
            }catch (e:Exception) {
                pageStatusData.postValue(PageStatus.error(e.toString()))
            }
        }
    }

    fun loadMoreData() {
        curPage++
        viewModelScope.launch {
            pageStatusData.postValue(PageStatus.loading())
            try {
                val articleResponse = homeApi.getArticles(curPage)
                articleData.postValue(WanDataWrapper.success(articleResponse.data.datas))

                pageStatusData.postValue(PageStatus.success())
            }catch (e:Exception) {
                pageStatusData.postValue(PageStatus.error(e.toString()))
            }
        }
    }

}